package com.ruoyi.common.utils.file;

import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * @author ：wk
 * @date ：Created in 2022/11/14 9:08
 */
public class PlanFileUtils {

    /**
    *@author: wk
    *@date: 2022/11/14 9:53
    *@description: 文件上传
    */
    public static void uploadFile(MultipartFile file, String savePath, String fileName) {
        try {
            // 路径不存在则创建文件夹
            File path = new File(savePath);
            if (!path.exists() && !path.isDirectory()){
                path.mkdirs();
            }

            InputStream inputStream = file.getInputStream();
            BufferedOutputStream bufferedOutputStream =
                    new BufferedOutputStream(Files.newOutputStream(Paths.get(savePath + "/" + fileName)));
            byte[] bytes = new byte[1024];
            int readLen;
            while ((readLen = inputStream.read(bytes)) != -1) {
                bufferedOutputStream.write(bytes, 0, readLen);
            }
            bufferedOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
    *@author: wk
    *@date: 2022/11/14 9:53
    *@description: 文件下载
    */

    public static void downExportFile(HttpServletResponse response, String filePath) {
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            File downloadFile = new File(filePath);
            if (!downloadFile.exists()) {
                response.setStatus(404);
                throw new RuntimeException("文件[" + filePath + "]不存在..");
            }
            // 设置强制下载不打开
            response.addHeader("Access-Contro1-A11ow-0rigin", "*");
            response.setContentType("application/force-download");
            response.addHeader("Content-Disposition", "attachment;fileName=" + new String(downloadFile.getName().getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));
            inputStream = new BufferedInputStream(Files.newInputStream(Paths.get(filePath)));
            outputStream = response.getOutputStream();
            byte[] buf = new byte[1024];
            int len;
            while ((len = inputStream.read(buf)) > 0) {
                outputStream.write(buf, 0, len);
            }
            response.flushBuffer();
            inputStream.close();
            outputStream.close();
        } catch (IOException e) {
            response.setStatus(404);
            e.printStackTrace();
        }
    }

}
